package com.promise.jokerdream.ui.components

import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import com.promise.jokerdream.model.formation.FormationAttrModel
import com.promise.jokerdream.model.formation.FormationListItemModel
import com.promise.jokerdream.model.formation.FormationTypeModel
import com.promise.jokerdream.model.formation.FormationSelection
import com.promise.jokerdream.model.formation.attrMap
import com.promise.jokerdream.ui.components.RoundCheckbox
import com.promise.jokerdream.ui.theme.AppFontSizes
import com.promise.jokerdream.ui.theme.AppSpacing
import com.promise.jokerdream.viewmodel.FormationViewModel

/**
 * 佣兵助阵选择半浮层
 */
@Composable
fun FormationSelectionBottomSheet(
    onDismiss: () -> Unit,
    onFormationSelect: (FormationTypeModel, FormationListItemModel, FormationAttrModel) -> Unit,
    selection: FormationSelection = FormationSelection.EMPTY
) {
    val compositionContext = rememberCompositionContext()
    
    // 创建 PMBottomSheetDialog
    val pmDialog = pmBottomSheetDialog(
        onDismiss = onDismiss,
        backgroundColor = 0xFFF8F9FA.toInt()
    )
    
    // 设置 Compose 内容
    pmDialog.setContent(compositionContext) {
        MaterialTheme {
            FormationSelectionContent(
                onDismiss = {
                    pmDialog.dismiss()
                    onDismiss()
                },
                onFormationSelect = { type, formation, attr ->
                    pmDialog.dismiss()
                    onFormationSelect(type, formation, attr)
                },
                selection = selection
            )
        }
    }
    
    // 显示对话框
    LaunchedEffect(Unit) {
        pmDialog.show()
    }

    // 清理资源
    DisposableEffect(Unit) {
        onDispose {
            pmDialog.dismiss()
        }
    }
}

/**
 * 佣兵助阵选择内容
 */
@Composable
private fun FormationSelectionContent(
    onDismiss: () -> Unit,
    onFormationSelect: (FormationTypeModel, FormationListItemModel, FormationAttrModel) -> Unit,
    selection: FormationSelection = FormationSelection.EMPTY
) {
    val viewModel: FormationViewModel = viewModel()
    var currentStep by remember { mutableStateOf(0) } // 0: 类型选择, 1: 组合选择, 2: 属性选择
    
    // 从ViewModel获取数据
    val formationTypes by viewModel.formationTypes.collectAsState()
    val selectedType by viewModel.selectedType.collectAsState()
    val formations by viewModel.formations.collectAsState()
    val selectedFormation by viewModel.selectedFormation.collectAsState()
    val attrs by viewModel.attrs.collectAsState()
    val selectedAttr by viewModel.selectedAttr.collectAsState()
    val isLoading by viewModel.isLoading.collectAsState()
    val isLoadingFormations by viewModel.isLoadingFormations.collectAsState()
    val isLoadingAttrs by viewModel.isLoadingAttrs.collectAsState()
    val errorMessage by viewModel.errorMessage.collectAsState()
    
    // 初始化选择状态 - 只在第一次打开时设置
    LaunchedEffect(Unit) {
        if (selection.isValid && selectedType == null) {
            val type = formationTypes.find { it.id == selection.selectedTypeId }
            if (type != null) {
                viewModel.selectType(type)
                currentStep = 1
                
                if (selection.selectedFormationId > 0) {
                    val formation = formations.find { it.id == selection.selectedFormationId }
                    if (formation != null) {
                        viewModel.selectFormation(formation)
                        currentStep = 2
                    }
                }
            }
        }
    }
    
    // 高度设置 - 参考SingleSelectBottomSheet
    val configuration = LocalConfiguration.current
    val screenHeight = configuration.screenHeightDp
    val height = with(screenHeight) {
        (screenHeight * 0.75).toInt().dp
    }
    
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .height(height)
            .padding(vertical = AppSpacing.pageVertical)
            .padding(horizontal = AppSpacing.pageHorizontal)
            .verticalScroll(rememberScrollState())
    ) {
        // 标准标题栏样式
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 取消按钮 - 左端
            Text(
                text = "取消",
                fontSize = AppFontSizes.body,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                modifier = Modifier.clickable { onDismiss() }
            )

            // 标题 - 居中
            Text(
                text = when (currentStep) {
                    0 -> "选择助阵类型"
                    1 -> "选择助阵组合"
                    2 -> "选择助阵属性"
                    else -> "佣兵助阵"
                },
                fontSize = AppFontSizes.h4,
                fontWeight = FontWeight.SemiBold,
                color = MaterialTheme.colorScheme.onSurface,
                textAlign = TextAlign.Center,
                modifier = Modifier.weight(1f)
            )

            // 完成按钮 - 右端（只在最后一步显示）
            if (currentStep == 2 && selectedType != null && selectedFormation != null && selectedAttr != null) {
                Text(
                    text = "完成",
                    fontSize = AppFontSizes.body,
                    color = MaterialTheme.colorScheme.primary,
                    fontWeight = FontWeight.Medium,
                    modifier = Modifier.clickable {
                        selectedType?.let { type ->
                            selectedFormation?.let { formation ->
                                selectedAttr?.let { attr ->
                                    onFormationSelect(type, formation, attr)
                                }
                            }
                        }
                    }
                )
            } else {
                // 占位符保持布局平衡
                Spacer(modifier = Modifier.width(40.dp))
            }
        }
        
        Spacer(modifier = Modifier.height(AppSpacing.componentLarge))
        
        // 加载状态
        if (isLoading) {
            Box(
                modifier = Modifier.fillMaxWidth(),
                contentAlignment = Alignment.Center
            ) {
                CircularProgressIndicator()
            }
        } else {
            // 第一层：助阵类型
            FormationTypeSection(
                types = formationTypes,
                selectedType = selectedType,
                onTypeSelected = { type ->
                    viewModel.selectType(type)
                    currentStep = 1
                }
            )
            
            // 第二层：助阵组合（只在选择了类型后显示）
            if (selectedType != null) {
                Spacer(modifier = Modifier.height(AppSpacing.componentLarge))
                FormationListSection(
                    formations = formations,
                    selectedFormation = selectedFormation,
                    isLoading = isLoadingFormations,
                    onFormationSelected = { formation ->
                        viewModel.selectFormation(formation)
                        currentStep = 2
                    }
                )
            }
            
            // 第三层：助阵属性（只在选择了组合后显示）
            if (selectedFormation != null) {
                Spacer(modifier = Modifier.height(AppSpacing.componentLarge))
                FormationAttrSection(
                    attrs = attrs,
                    selectedAttr = selectedAttr,
                    isLoading = isLoadingAttrs,
                    onAttrSelected = { attr ->
                        viewModel.selectAttr(attr)
                    }
                )
            }
        }
        
        // 重试按钮 - 在内容区域下方
        errorMessage?.let {
            Spacer(modifier = Modifier.height(AppSpacing.componentLarge))
            
            Box(
                modifier = Modifier.fillMaxWidth(),
                contentAlignment = Alignment.Center
            ) {
                TextButton(
                    onClick = { viewModel.retry() }
                ) {
                    Icon(
                        imageVector = Icons.Default.Refresh,
                        contentDescription = "重试",
                        tint = MaterialTheme.colorScheme.primary,
                        modifier = Modifier.size(18.dp)
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(
                        text = "重试",
                        color = MaterialTheme.colorScheme.primary
                    )
                }
            }
        }
    }
}

/**
 * 第一层：助阵类型选择区域
 */
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun FormationTypeSection(
    types: List<FormationTypeModel>,
    selectedType: FormationTypeModel?,
    onTypeSelected: (FormationTypeModel) -> Unit
) {
    Column {
        // 标题
        Text(
            text = "助阵类型",
            fontSize = AppFontSizes.h5,
            fontWeight = FontWeight.SemiBold,
            color = MaterialTheme.colorScheme.onSurface,
            modifier = Modifier.padding(bottom = AppSpacing.componentMedium)
        )
        
        // 内容 - 使用FlowRow从左到右展示
        FlowRow(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(AppSpacing.componentMedium),
            verticalArrangement = Arrangement.spacedBy(AppSpacing.componentMedium)
        ) {
            types.forEach { type ->
                AppChip(
                    text = type.name,
                    isSelected = selectedType?.id == type.id,
                    onClick = { onTypeSelected(type) }
                )
            }
        }
    }
}

/**
 * 第二层：助阵组合选择区域
 */
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun FormationListSection(
    formations: List<FormationListItemModel>,
    selectedFormation: FormationListItemModel?,
    isLoading: Boolean,
    onFormationSelected: (FormationListItemModel) -> Unit
) {
    Column {
        // 标题
        Text(
            text = "助阵组合",
            fontSize = AppFontSizes.h5,
            fontWeight = FontWeight.SemiBold,
            color = MaterialTheme.colorScheme.onSurface,
            modifier = Modifier.padding(bottom = AppSpacing.componentMedium)
        )
        
        // 内容 - 使用FlowRow从左到右展示
        if (isLoading) {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(32.dp), // 与AppChip高度一致
                contentAlignment = Alignment.Center
            ) {
                CircularProgressIndicator(
                    modifier = Modifier.size(20.dp) // 调整loading大小
                )
            }
        } else {
            FlowRow(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(AppSpacing.componentMedium),
                verticalArrangement = Arrangement.spacedBy(AppSpacing.componentMedium)
            ) {
                formations.forEach { formation ->
                    AppChip(
                        text = formation.name,
                        isSelected = selectedFormation?.id == formation.id,
                        onClick = { onFormationSelected(formation) }
                    )
                }
            }
        }
    }
}

/**
 * 第三层：助阵属性选择区域
 */
@Composable
private fun FormationAttrSection(
    attrs: List<FormationAttrModel>,
    selectedAttr: FormationAttrModel?,
    isLoading: Boolean,
    onAttrSelected: (FormationAttrModel) -> Unit
) {
    Column {
        // 标题
        Text(
            text = "助阵属性",
            fontSize = AppFontSizes.h5,
            fontWeight = FontWeight.SemiBold,
            color = MaterialTheme.colorScheme.onSurface,
            modifier = Modifier.padding(bottom = AppSpacing.componentMedium)
        )
        
        // 内容 - 从上到下布局
        if (isLoading) {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(48.dp), // 与FormationAttrItem高度一致
                contentAlignment = Alignment.Center
            ) {
                CircularProgressIndicator(
                    modifier = Modifier.size(20.dp) // 调整loading大小
                )
            }
        } else {
            Column(
                verticalArrangement = Arrangement.spacedBy(AppSpacing.componentSmall)
            ) {
                attrs.forEach { attr ->
                    FormationAttrItem(
                        attr = attr,
                        isSelected = selectedAttr?.type == attr.type,
                        onSelected = { onAttrSelected(attr) }
                    )
                }
            }
        }
    }
}

/**
 * 助阵属性项
 */
@Composable
private fun FormationAttrItem(
    attr: FormationAttrModel,
    isSelected: Boolean,
    onSelected: () -> Unit
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clickable(
                interactionSource = remember { MutableInteractionSource() },
                indication = null
            ) { onSelected() }
            .padding(vertical = AppSpacing.componentSmall),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(AppSpacing.componentMedium)
    ) {
        // RoundCheckbox
        RoundCheckbox(
            checked = isSelected,
            onCheckedChange = { if (it) onSelected() }
        )
        
        // 属性信息 - 单行显示
        Row(
            modifier = Modifier.weight(1f),
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 属性名称
            Text(
                text = "${attrMap[attr.type] ?: "未知属性"} ",
                fontSize = AppFontSizes.body,
                fontWeight = FontWeight.Medium,
                color = MaterialTheme.colorScheme.onSurface
            )
            // 等级和经验 - 使用desc样式
            Text(
                text = "(等级: ${attr.level}, 经验: ${attr.curExp}/${attr.exp})",
                fontSize = AppFontSizes.mediumBody,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }
    }
}
